package chu.dejian.ui.unused;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.sam.ble.unimplements.BLEBRHelper;
import com.sam.blemodule.R;
import com.sam.ui.base.fragment.BaseFragment;
import com.sam.utils.L;
import com.sam.utils.T;
import com.sam.utils.display.DensityUtils;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenu;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenuCreator;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenuItem;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenuListView;

import java.util.ArrayList;
import java.util.List;

import chu.dejian.adapter.AttentionAdapter;
import chu.dejian.entity.ContactEntity;
import chu.dejian.entity.SendedRequestEntity;
import chu.dejian.models.GetSendedAttenderRequestResponse;
import chu.dejian.models.PostAttenderRequestRequest;
import chu.dejian.models.PostAttenderRequestResponse;
import chu.dejian.restApi.RestClient;
import chu.dejian.ui.activity.AttentionApplyActivity;
import chu.dejian.widget.AttentionLevelView;
import chu.dejian.widget.ViewPagerNavBar;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class AttentionSendedRequestFragment extends BaseFragment {
	private static AttentionSendedRequestFragment instance;
	private ViewPagerNavBar navBar;
	private ViewPager viewpager;

	private AttentionAdapter consentedAdapter,pendingAdapter,refusedAdapter;
	private List<ContactEntity> consentedRequestList, pendingRequestList, refusedRequestList;

	private static final int UPDATE_CONSENTED_REQUEST = 0;
	private static final int UPDATE_PENDING_REQUEST = 1;
	private static final int UPDATE_REFUSED_REQUEST = 2;
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what){
				case UPDATE_CONSENTED_REQUEST:
					navBar.setTabTagText(0,(int)msg.obj+"");
					consentedAdapter.notifyDataSetChanged();
					break;
				case UPDATE_PENDING_REQUEST:
					navBar.setTabTagText(1,(int)msg.obj+"");
					pendingAdapter.notifyDataSetChanged();
					break;
				case UPDATE_REFUSED_REQUEST:
					navBar.setTabTagText(2,(int)msg.obj+"");
					refusedAdapter.notifyDataSetChanged();
					break;
			}
			super.handleMessage(msg);
		}
	};
	private void sendMessage(int msgWhat,Object msgObj){
		Message msg = new Message();
		msg.what = msgWhat;
		msg.obj = msgObj;
		handler.sendMessage(msg);
	}

	private AnsyncSendedRequestThread ansyncSendedRequestThread = new AnsyncSendedRequestThread();

	public synchronized static AttentionSendedRequestFragment getInstance(){
		if(instance == null){
			instance = new AttentionSendedRequestFragment();
		}
		return instance;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_attention_to_me);
	}

	public void findView() {
		navBar = (ViewPagerNavBar) findViewById(R.id.nav_bar);
		viewpager = (ViewPager) findViewById(R.id.view_pager);
	}

	public void initView() {
		ListView consentedListView = new ListView(getActivity());
		ListView pendingListView = new ListView(getActivity());
		SwipeMenuListView refusedListView = new SwipeMenuListView(getActivity());

		ViewPager.LayoutParams lp = new ViewPager.LayoutParams();
		lp.width = ViewPager.LayoutParams.MATCH_PARENT;
		lp.height = ViewPager.LayoutParams.MATCH_PARENT;

		consentedListView.setLayoutParams(lp);
		pendingListView.setLayoutParams(lp);
		refusedListView.setLayoutParams(lp);

		Drawable sepratorLineDrawable = new ColorDrawable(getResources().getColor(R.color.separator_line_bg));
		consentedListView.setDivider(sepratorLineDrawable);
		pendingListView.setDivider(sepratorLineDrawable);
		refusedListView.setDivider(sepratorLineDrawable);
		consentedListView.setDividerHeight(1);
		pendingListView.setDividerHeight(1);
		refusedListView.setDividerHeight(1);

		refusedListView.setMenuCreator(creator);
		refusedListView.setOnMenuItemClickListener(onMenuItemClickListener);
//		refusedListView.setOnItemClickListener(onItemClickListener);
		refusedListView.setOnSwipeListener(onSwipeListener);

		consentedRequestList = new ArrayList<ContactEntity>();
		pendingRequestList = new ArrayList<ContactEntity>();
		refusedRequestList = new ArrayList<ContactEntity>();

		consentedAdapter = new AttentionAdapter(getActivity(), R.layout.row_attention_vertical, consentedRequestList,false);
		pendingAdapter = new AttentionAdapter(getActivity(), R.layout.row_attention_vertical, pendingRequestList,false);
		refusedAdapter = new AttentionAdapter(getActivity(), R.layout.row_attention_vertical, refusedRequestList,false);

		consentedListView.setAdapter(consentedAdapter);
		pendingListView.setAdapter(pendingAdapter);
		refusedListView.setAdapter(refusedAdapter);

		List<View> pages = new ArrayList<View>();
		pages.add(consentedListView);
		pages.add(pendingListView);
		pages.add(refusedListView);

		navBar.setPages(viewpager,pages);
		navBar.setCurrentTab(0);
		navBar.setOnPageChangeCallback(new ViewPagerNavBar.OnPageChangeCallback(){
			@Override
			public void onPageChanged(final int position) {
				handler.postDelayed(new Runnable() {
					@Override
					public void run() {
						navBar.hideTabTag(position);
					}
				},10000);
			}
		});
	}

	@Override
	public void onResume() {
		super.onResume();
		newConsentedCounts = newPendingCounts = newRefusedCounts = 0;
		ansyncSendedRequestThread.start();
		navBar.resetCursorLine();
	}

	private boolean isAnsyncRequest = false;
	private static int newConsentedCounts = 0,newPendingCounts = 0,newRefusedCounts = 0;
	public void AsyncSendedAttentionRequests(int startPage){

		if(isAnsyncRequest) return;
		isAnsyncRequest = true;

		RestClient.getAuthedClient().getApiService().getSendedAttenderRequest(startPage,new Callback<GetSendedAttenderRequestResponse>() {
			@Override
			public void success(GetSendedAttenderRequestResponse getSendedAttenderRequestResponse, Response response) {
				if(response.getStatus() == 401) {
					BLEBRHelper.getInstance().sendReloginBR(getActivity());
					T.showShort(getActivity(),R.string.nauthorized_and_relogin);
					return;
				}
				L.d("《获取已发送的关注请求-getReceivedAttenderRequest》\n请求成功： \n\t返回数据：" + getSendedAttenderRequestResponse.toString());
				final List<GetSendedAttenderRequestResponse.ResultsEntity> resultEntities = getSendedAttenderRequestResponse.getResults();
				if (resultEntities == null || resultEntities.size() == 0) return;
				for (GetSendedAttenderRequestResponse.ResultsEntity resultsEntity : resultEntities) {
					ContactEntity newContactEntity = new ContactEntity(resultsEntity.getName(), resultsEntity.getAttender(),resultsEntity.getAttendee_level());
					switch (resultsEntity.getStatus()){
						case SendedRequestEntity.STATUS_CONSENTED:
							if(consentedRequestList.contains(newContactEntity)) break;
							newConsentedCounts++;
							consentedRequestList.add(newContactEntity);
							break;
						case SendedRequestEntity.STATUS_PENDING:
							if(pendingRequestList.contains(newContactEntity)) break;
							newPendingCounts++;
							pendingRequestList.add(newContactEntity);
							break;
						case SendedRequestEntity.STATUS_REFUSED:
							if(refusedRequestList.contains(newContactEntity)) break;
							newRefusedCounts++;
							refusedRequestList.add(newContactEntity);
							break;
						case SendedRequestEntity.STATUS_TIMEOUT:

							break;
					}
				}
				isAnsyncRequest = false;
				if(getSendedAttenderRequestResponse.getNext() != null && !getSendedAttenderRequestResponse.getNext().equals("null")){
					int nextPage = Integer.parseInt(Uri.parse(getSendedAttenderRequestResponse.getNext()).getQueryParameter("page"));
					AsyncSendedAttentionRequests(nextPage);
				} else {
					if(newConsentedCounts > 0) sendMessage(UPDATE_CONSENTED_REQUEST,newConsentedCounts);
					if(newPendingCounts > 0) sendMessage(UPDATE_PENDING_REQUEST,newPendingCounts);
					if(newRefusedCounts > 0) sendMessage(UPDATE_REFUSED_REQUEST,newRefusedCounts);
				}
			}

			@Override
			public void failure(RetrofitError retrofitError) {
				L.d("《获取已发送的关注请求-getReceivedAttenderRequest》\n请求失败： \n\t错误信息：" + retrofitError.toString());
				T.showLong(getActivity(),R.string.get_data_from_webserver_failed);
			}
		});
	}

	private SwipeMenuListView.OnMenuItemClickListener onMenuItemClickListener = new SwipeMenuListView.OnMenuItemClickListener() {
		@Override
		public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
			final int p = refusedRequestList.size() - 1 - position;
			final ContactEntity contactEntity = refusedRequestList.get(p);
			switch (index) {
				case 0: //重发
					PostAttenderRequestRequest request = new PostAttenderRequestRequest(contactEntity.contactPhoneNum, contactEntity.attentionLevel.ordinal(), contactEntity.contactName);
					RestClient.getAuthedClient().getApiService().postAttenderRequest(request, new Callback<PostAttenderRequestResponse>() {
						@Override
						public void success(PostAttenderRequestResponse postAttenderRequestResponse, Response response) {
							if(response.getStatus() == 401) {
								BLEBRHelper.getInstance().sendReloginBR(getActivity());
								T.showShort(getActivity(),R.string.nauthorized_and_relogin);
								return;
							}
							String requestStr = postAttenderRequestResponse == null ? "null" : postAttenderRequestResponse.toString();
							L.d("《用户提交关注请求-postAttenderRequest》" + "\n" + "请求成功： \n\t返回数据：" + requestStr);// + "\n\t响应数据：" + printResponse(response));
							if(response.getStatus() == 201) T.showLong(getActivity(),R.string.resend_succeeded);
							else T.showLong(getActivity(),R.string.resend_failed);
						}

						@Override
						public void failure(RetrofitError retrofitError) {
							L.d("《用户提交关注请求-postAttenderRequest》"+"\n"+ "请求失败： \n\t错误信息：" + retrofitError.toString());
							T.showLong(getActivity(),R.string.resend_failed);
						}
					});
					break;
				case 1: //修改
					Intent intent = new Intent(getActivity(),AttentionApplyActivity.class);
					intent.putExtra(AttentionApplyActivity.EXTRA_KEY_CONTACT_NAME, contactEntity.contactName);
					intent.putExtra(AttentionApplyActivity.EXTRA_KEY_CONTACT_PHONE, contactEntity.contactPhoneNum);
					intent.putExtra(AttentionApplyActivity.EXTRA_KEY_CONTACT_LEVEL, contactEntity.attentionLevel == null ? -1 : contactEntity.attentionLevel.ordinal());
					startActivity(intent);
					break;
				case 2: //删除
					request = new PostAttenderRequestRequest(contactEntity.contactPhoneNum, AttentionLevelView.ATTENTION_LEVEL.NOTIFY_NOTHING.ordinal(), contactEntity.contactName);
					RestClient.getAuthedClient().getApiService().postAttenderRequest(request, new Callback<PostAttenderRequestResponse>() {
						@Override
						public void success(PostAttenderRequestResponse postAttenderRequestResponse, Response response) {
							if(response.getStatus() == 401) {
								BLEBRHelper.getInstance().sendReloginBR(getActivity());
								T.showShort(getActivity(),R.string.nauthorized_and_relogin);
								return;
							}
							String requestStr = postAttenderRequestResponse == null ? "null" : postAttenderRequestResponse.toString();
							L.d("《用户提交关注请求-postAttenderRequest》" + "\n" + "请求成功： \n\t返回数据：" + requestStr);// + "\n\t响应数据：" + printResponse(response));
							if(response.getStatus() == 201) {
								refusedRequestList.remove(p);
								refusedAdapter.notifyDataSetChanged();
							} else T.showLong(getActivity(),R.string.delete_failed);
						}

						@Override
						public void failure(RetrofitError retrofitError) {
							L.d("《用户提交关注请求-postAttenderRequest》"+"\n"+ "请求失败： \n\t错误信息：" + retrofitError.toString());
							T.showLong(getActivity(), R.string.delete_failed);
						}
					});
					break;
			}
			return false;
		}
	};

	private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			T.showShort(getActivity(),position + " 项被点击");
		}
	};

	SwipeMenuCreator creator = new SwipeMenuCreator() {

		@Override
		public void create(SwipeMenu menu) {
			SwipeMenuItem resendBtn = new SwipeMenuItem(getActivity());
			Drawable resendBg = new ColorDrawable(getResources().getColor(R.color.green_menu_bg_color));
			resendBtn.setBackground(resendBg);
			resendBtn.setWidth(DensityUtils.dp2px(getActivity(), 60));
			resendBtn.setTitle(R.string.resend);
			resendBtn.setTitleSize(16);
			resendBtn.setTitleColor(Color.WHITE);
			menu.addMenuItem(resendBtn);

			SwipeMenuItem modifyBtn = new SwipeMenuItem(getActivity());
			Drawable modifyBg = new ColorDrawable(getResources().getColor(R.color.cyan_menu_bg_color));
			modifyBtn.setBackground(modifyBg);
			modifyBtn.setWidth(DensityUtils.dp2px(getActivity(), 60));
			modifyBtn.setTitle(R.string.modify);
			modifyBtn.setTitleSize(16);
			modifyBtn.setTitleColor(Color.WHITE);
			menu.addMenuItem(modifyBtn);

			SwipeMenuItem deleteBtn = new SwipeMenuItem(getActivity());
			Drawable deleteBg = new ColorDrawable(getResources().getColor(R.color.orange_menu_bg_color));
			deleteBtn.setBackground(deleteBg);
			deleteBtn.setWidth(DensityUtils.dp2px(getActivity(), 60));
			deleteBtn.setTitle(R.string.delete);
			deleteBtn.setTitleSize(16);
			deleteBtn.setTitleColor(Color.WHITE);
			menu.addMenuItem(deleteBtn);
		}
	};

	private SwipeMenuListView.OnSwipeListener onSwipeListener = new SwipeMenuListView.OnSwipeListener() {

		@Override
		public void onSwipeStart(int position) {
			// swipe start
		}

		@Override
		public void onSwipeEnd(int position) {
			// swipe end
		}
	};

	class AnsyncSendedRequestThread implements Runnable {
		public boolean running = false;
		private Thread thread = null;

		public void run() {
			AsyncSendedAttentionRequests(1);
		}

		public void start() {
			try {
				this.thread = new Thread(this);
				this.running = true;
				this.thread.start();
			} finally {
			}
		}

		public void stop() {
			try {
				this.running = false;
				this.thread = null;
			} finally {
			}
		}
	}

}
